<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="套餐名" prop="packageName">
        <el-input
          v-model="queryParams.packageName"
          placeholder="请输入套餐名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="餐馆" prop="resId">
        <el-select
            v-model="queryParams.resId"
            placeholder="请选择餐馆"
            clearable
            style="width: 200px"
        >
          <el-option
              v-for="resinfo in resinfoList"
              :key="resinfo.resId"
              :label="resinfo.resName"
              :value="resinfo.resId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:respackage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:respackage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="respackageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="排序" align="center">
        <template #default="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="套餐图片" align="center" prop="imgUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imgUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="套餐" align="center" prop="packageName" />
      <el-table-column label="餐馆" align="center" prop="resInfo.resName" />
      <el-table-column label="单价" align="center" prop="unitPrice" />
      <el-table-column label="现价" align="center">
        <template #default="scope">
          <!-- 处理空值和非数字情况，避免计算错误 -->
          {{ calculateCurrentPrice(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="销售量" align="center" prop="salesVolume" />
      <el-table-column label="有效期" align="center" prop="validPeriod" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:respackage:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:respackage:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改餐馆套餐对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="respackageRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="套餐名" prop="packageName">
          <el-input v-model="form.packageName" placeholder="请输入套餐名" />
        </el-form-item>
        <el-form-item label="套餐图片" prop="imgUrl">
          <image-upload v-model="form.imgUrl"/>
        </el-form-item>
        <el-form-item label="餐馆" prop="resId">
          <el-select v-model="form.resInfo.resName" placeholder="请选择状态" @change="handleresInfoChange">
            <el-option
                v-for="resinfo in resinfoList"
                :key="resinfo.resId"
                :label="resinfo.resName"
                :value="resinfo.resId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="form.unitPrice" placeholder="请输入套餐单价" />
        </el-form-item>
        <el-form-item label="套餐折扣" prop="discount">
          <el-input v-model="form.discount" placeholder="请输入套餐折扣" />
        </el-form-item>
        <el-form-item label="套餐介绍" prop="packageDesc">
          <el-input v-model="form.packageDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="销售量" prop="salesVolume">
          <el-input disabled v-model="form.salesVolume" placeholder="请输入销售量" />
        </el-form-item>
        <el-form-item label="有效期" prop="validPeriod">
          <el-date-picker clearable
            v-model="form.validPeriod"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Respackage">
import {
  listRespackage,
  getRespackage,
  delRespackage,
  addRespackage,
  updateRespackage,
  listRespackage1
} from "@/api/system/respackage"
import { listResinfo } from "@/api/system/resinfo"
import { ref, reactive, toRefs, onMounted } from 'vue'

import useUserStore from "@/store/modules/user.js";
import {addRespakdish as addRespakdishApi, addRespakdish, listRespakdish} from "@/api/system/respakdish.js";
import {listResdish} from "@/api/system/resdish.js";

const userStore = useUserStore()
console.log(userStore)

const { proxy } = getCurrentInstance()

const respackageList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const resinfoList = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    packageName: null,
    imgUrl: null,
    unitPrice: null,
    discount: null,
    packageDesc: null,
    salesVolume: null,
    resId: null,
    validPeriod: null,
    field: null,
    resInfo: {
      resId: null,
      resName: null,
      avgPrice: null,
      address: null,
      imgUrl: null,
      groupBuyCount: null,
      serviceTel: null,
      resDesc: null,
      userId: null,
      status: null,
      province: null,
      city: null,
      district: null,
      categoryId: null,
      notice: null,
      overallScore: null,
      field: null
    }
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询餐馆套餐列表 */
function getList() {
  loading.value = true
  const userId = userStore.id;
  console.log('userId:', userId)
  if (userId && userId !== 1) {
    listRespackage1(queryParams.value, userId).then(response => {
      respackageList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }else {
    listRespackage(queryParams.value).then(response => {
      respackageList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    packageId: null,
    packageName: null,
    imgUrl: null,
    unitPrice: null,
    discount: null,
    packageDesc: null,
    salesVolume: null,
    resId: null,
    validPeriod: null,
    field: null,
    resInfo: {
      resId: null,
      resName: null,
      avgPrice: null,
      address: null,
      imgUrl: null,
      groupBuyCount: null,
      serviceTel: null,
      resDesc: null,
      userId: null,
      status: null,
      province: null,
      city: null,
      district: null,
      categoryId: null,
      notice: null,
      overallScore: null,
      field: null
    }
  }
  proxy.resetForm("respackageRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.resId = null
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.packageId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加餐馆套餐"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _packageId = row.packageId || ids.value
  getRespackage(_packageId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改餐馆套餐"
  })
}

// 处理类别选择变化
function handleresInfoChange(newValue) {
  form.value.resId = newValue
  // 同时更新 resCategory 对象中的 categoryId
  form.value.resInfo.resId = newValue
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["respackageRef"].validate(valid => {
    if (valid) {
      if (form.value.packageId != null) {
        updateRespackage(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRespackage(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()

          listRespackage({pageNum: 1, pageSize: 100000}).then(response => {
            respackageList.value = response.rows
            console.log('respackageList', respackageList)

            const lastPackage = respackageList.value[respackageList.value.length - 1]
            if (lastPackage) {
              const respakdishData = {
                relationId: lastPackage.packageId,
                treeName: lastPackage.packageName
              };

              addRespakdish(respakdishData).then(response => {
                console.log('菜品信息新增成功', response);

                listRespakdish({pageNum: 1, pageSize: 100000}).then(listResponse => {
                  console.log('listResponse:', listResponse)
                  const respakdishList = listResponse.data;
                  console.log('respakdishList:', respakdishList)
                  if (respakdishList.length > 0) {
                    // 获取列表的最后一项菜品数据的 treeId 的值
                    const pId = respakdishList[respakdishList.length - 1].treeId;

                    // 将 pId 赋值给 relationId
                    const respakdishData3 = {
                      relationId: 1003,
                      treeName: '其他',
                      pId: pId
                    }

                    const respakdishData2 = {
                      relationId: 1002,
                      treeName: '主食',
                      pId: pId
                    }

                    const respakdishData1 = {
                      relationId: 1001,
                      treeName: '菜品',
                      pId: pId
                    }

                    // 调用respackdish.js的新增操作
                    addRespakdish(respakdishData1).then(response => {
                      console.log('菜品信息新增成功', response);

                      addRespakdish(respakdishData2).then(response => {
                        console.log('菜品信息新增成功', response);

                        addRespakdish(respakdishData3).then(response => {
                          console.log('菜品信息新增成功', response);
                        });

                      });

                    });

                  } else {
                    console.log('未获取到菜品列表');
                  }
                })

              })
            }
          })
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _packageIds = row.packageId || ids.value
  proxy.$modal.confirm('是否确认删除餐馆套餐编号为"' + _packageIds + '"的数据项？').then(function() {
    return delRespackage(_packageIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/respackage/export', {
    ...queryParams.value
  }, `respackage_${new Date().getTime()}.xlsx`)
}

/** 计算套餐现价方法 */
function calculateCurrentPrice(row) {
  // 处理单价和折扣为空的情况
  if (!row.unitPrice || !row.discount) return '--'

  // 确保数值类型（避免字符串类型导致计算错误）
  const unitPrice = parseFloat(row.unitPrice)
  const discount = parseFloat(row.discount)

  // 计算逻辑：单价 * (折扣/10)，保留两位小数
  return (unitPrice * (discount / 10)).toFixed(2)
}

onMounted(() => {
  const userId = userStore.id;
  if (userId && userId !== 1) {
    listResinfo({userId}).then(response => {
      resinfoList.value = response.rows
    })
  }else {
    listResinfo().then(response => {
      resinfoList.value = response.rows
    })
  }
})

getList()
</script>
